﻿using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace SyncDBMSSQL {
    public partial class frmChangeConnection : Form {

        private string _connectionString = "";
        private SqlConnectionStringBuilder cns = new SqlConnectionStringBuilder();

        public string ConnectionString {
            get {
                return _connectionString;
            }
            set {
                _connectionString = value;
                if (_connectionString.Trim().Length > 0) {
                    cns = new SqlConnectionStringBuilder(_connectionString);
                    ddlServer.Text = cns.DataSource;

                    if (cns.IntegratedSecurity) {
                        rbUseWindowsAuth.Checked = true;
                    }
                    else {
                        rbUseSQLAuth.Checked = true;
                        txUser.Text = cns.UserID;
                        txPassword.Text = cns.Password;
                    }
                    
                    ddlDataBase.Text = cns.InitialCatalog;
                }
            }
        }

        public frmChangeConnection() {
            InitializeComponent();
        }

        private void frmChangeConnection_Load(object sender, EventArgs e) {
        }

        private void rbUseWindowsAuth_CheckedChanged(object sender, EventArgs e) {
            txUser.Enabled = false;
            txPassword.Enabled = false;
            ddlDataBase.Items.Clear();
        }

        private void rbUseSQLAuth_CheckedChanged(object sender, EventArgs e) {
            txUser.Enabled = true;
            txPassword.Enabled = true;
            ddlDataBase.Items.Clear();
        }

        private void ddlDataBase_DropDown(object sender, EventArgs e) {
            if (ddlDataBase.Items.Count == 0) {
                // Crea un string de conexión
                cns = new SqlConnectionStringBuilder();
                cns.DataSource = ddlServer.Text;
                if (rbUseWindowsAuth.Checked)
                    cns.IntegratedSecurity = true;
                else {
                    cns.IntegratedSecurity = false;
                    cns.UserID = txUser.Text;
                    cns.Password = txPassword.Text;
                }

                this.Cursor = Cursors.WaitCursor;

                // Obtiene la lista de bases de datos a las que tiene acceso la conexión
                try {
                    SqlConnection con = new SqlConnection(cns.ConnectionString);
                    con.Open();

                    System.Data.DataTable tblDatabases = con.GetSchema("Databases");
                    foreach (System.Data.DataRow rowDatabase in tblDatabases.Rows) {
                        ddlDataBase.Items.Add(rowDatabase["database_name"].ToString());
                    }
                    con.Close();
                }
                catch (SqlException ex) {
                    MessageBox.Show(ex.Message, "Error de Conexión", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.Cursor = Cursors.Default;
            }
        }

        private void btRefreshServers_Click(object sender, EventArgs e) {
            ddlServer.Items.Clear();
            this.Cursor = Cursors.WaitCursor;

            try {
                // Retrieve the enumerator instance and then the data.
                SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
                System.Data.DataTable tblServers = instance.GetDataSources();

                foreach (DataRow rowServer in tblServers.Rows) {
                    if (rowServer["InstanceName"].ToString().Trim().Length > 0)
                        ddlServer.Items.Add(string.Format("{0}\\{1}", rowServer["ServerName"].ToString(), rowServer["InstanceName"].ToString()));
                    else
                        ddlServer.Items.Add(rowServer["ServerName"].ToString());
                }
            }
            catch (DataException ex) {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }

        private void btTest_Click(object sender, EventArgs e) {
            TestConnection(true);
        }

        private void ddlServer_SelectedIndexChanged(object sender, EventArgs e) {
            ddlDataBase.Items.Clear();
        }

        private void btOk_Click(object sender, EventArgs e) {
            if (TestConnection(false)) {
                this.DialogResult = DialogResult.OK;
                this.Hide();
            }
        }

        private bool TestConnection(bool showTestMessage) {
            bool retval = false;

            if (ddlServer.Text.Trim().Length == 0) {
                MessageBox.Show("Debe especificar el nombre o IP del servidor", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return retval;
            }

            if (ddlDataBase.Text.Trim().Length == 0) {
                MessageBox.Show("Debe especificar el nombre de la base de datos", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return retval;
            }

            // Crea un string de conexión
            cns = new SqlConnectionStringBuilder();
            cns.DataSource = ddlServer.Text;
            cns.InitialCatalog = ddlDataBase.Text;
            if (rbUseWindowsAuth.Checked)
                cns.IntegratedSecurity = true;
            else {
                cns.IntegratedSecurity = false;
                cns.UserID = txUser.Text;
                cns.Password = txPassword.Text;
            }

            this.Cursor = Cursors.WaitCursor;

            // Obtiene la lista de bases de datos a las que tiene acceso la conexión
            try {
                SqlConnection con = new SqlConnection(cns.ConnectionString);
                con.Open();
                con.Close();
                _connectionString = cns.ConnectionString;

                if (showTestMessage) MessageBox.Show("Prueba de Conexión Exitosa", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                retval = true;
            }
            catch (SqlException ex) {
                MessageBox.Show(ex.Message, "Error de Conexión", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            this.Cursor = Cursors.Default;
            return retval;
        }
    }
}
